import java.util.ArrayList;
import java.util.List;

class Solution2 {
    List<String> ret;
    StringBuilder path;
    int left = 0, right = 0;
    public List<String> generateParenthesis(int n) {
        ret = new ArrayList<>();
        path = new StringBuilder();
        dfs(n);
        return ret;
    }
    private void dfs(int n) {
        if (right == n) {
            ret.add(path.toString());
            return;
        }
        if (left < n) {
            path.append('(');
            left++;
            dfs(n);
            path.deleteCharAt(path.length() - 1);
            left--;
        }
        if (right < left) {
            path.append(')');
            right++;
            dfs(n);
            path.deleteCharAt(path.length() - 1);
            right--;
        }
    }
}